<template>
  <div class="category-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" class="search-form">
        <div class="search-item">
          <el-input v-model="searchForm.keyword" placeholder="搜索分类名称或描述" clearable @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>

        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <div class="table-header">
        <div class="table-title">分类列表</div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            添加分类
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="categories" stripe>
        <el-table-column prop="name" label="分类名称" min-width="150" />

        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="{ row }">
            <span>{{ row.description || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="bookCount" label="图书数量" width="100" align="center" />

        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>

            <el-button type="danger" size="small" @click="handleDelete(row)" :disabled="row.bookCount > 0">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑分类' : '添加分类'" width="500px">
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryRules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="categoryForm.description" type="textarea" :rows="3" placeholder="请输入分类描述" maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryList, createCategory, updateCategory, deleteCategory } from '@/api/category'
import {
  Search,
  Refresh,
  Plus
} from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)

// 表单引用
const categoryFormRef = ref()

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 数据
const categories = ref([])

// 分类表单
const categoryForm = reactive({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

// 加载分类列表
const loadCategories = async () => {
  try {
    loading.value = true

    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await getCategoryList(params)
    console.log('---------', response.data)

    categories.value = response.data
    pagination.total = 10000
  } catch (error) {
    console.error('加载分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadCategories()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  pagination.current = 1
  loadCategories()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadCategories()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadCategories()
}

// 添加分类
const handleAdd = () => {
  isEdit.value = false
  Object.assign(categoryForm, {
    id: null,
    name: '',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (category) => {
  isEdit.value = true
  Object.assign(categoryForm, {
    id: category.id,
    name: category.name,
    description: category.description || ''
  })
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (category) => {
  if (category.bookCount > 0) {
    ElMessage.warning('该分类下还有图书，无法删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除分类「${category.name}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteCategory(category.id)
    ElMessage.success('删除成功')
    loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!categoryFormRef.value) return

  try {
    await categoryFormRef.value.validate()

    submitting.value = true

    if (isEdit.value) {
      await updateCategory(categoryForm.id, categoryForm)
      ElMessage.success('更新分类成功')
    } else {
      await createCategory(categoryForm)
      ElMessage.success('创建分类成功')
    }

    dialogVisible.value = false
    loadCategories()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 初始化
onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.category-list {
  max-width: 1200px;
  margin: 0 auto;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-item {
    min-width: auto;
  }

  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>